<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );

class Admin_Resources extends Admin_Controller {
	private $_modules = array ();
	private $_role = null;
	private $_checkedNodes = array ();
	
	private $rules = array ('first_name' => "required|alpha_dash", 'last_name' => "required|alpha_dash", 'password' => "min_length[6]|max_length[20]", // will be required when adding1
'confirm_password' => "matches[password]", 'email' => "required|valid_email", 'role' => "required", 'is_active' => "" );
	
	function __construct() {
		parent::Admin_Controller ();
		$this->load->library ( 'session' );
		$this->load->helper ( 'session' );
		$this->load->model ( 'users_m' );
		$this->load->model ( 'roles_m' );
		$this->load->model ( 'resources_m' );
		$this->load->model ( 'permissions_m' );
		$this->load->model ( 'modules_m' );
		$this->lang->load ( 'user' );
		$this->lang->load ( 'authorizations' );
		
		// Load resources
		$this->modules = $this->modules_m->getModules();
	}
	
	// Admin: List all User
	function index($role = '') {
		if (! $role)
			redirect ( 'admin/authorizations/admin_roles' );
		
		$this->_role = $role;
		$allowResources = $this->permissions_m->getPermissions ( array ('role' => $this->_role, 'allow' => 1 ) );
		$checkedIds = array ();
		if ($allowResources) {
			foreach ( $allowResources as $allowResource ) {
				if (! $allowResource->privilege)
					$checkedIds [] = $allowResource->resource;
				else
					$checkedIds [] = $allowResource->resource . "/" . $allowResource->privilege;
			}
		}
		
		$this->prepareJsonTree ( $checkedIds );
		$this->data->checkedIds = implode ( ",", $checkedIds );
		$this->data->role = $this->_role;
		
		$this->data->toolbar = createToolbar(array(array('command' => 'submit', 'label'=>$this->lang->line( 'permission_update_label' )), array('command' => 'Cancel', 'attribute'=>'class="btn_admin"')), array ('label' => sprintf($this->lang->line( 'role_edit_resource_header'), $this->data->role), 'attribute' => 'class = "acc_permission toolbar_title"' ) );
		$this->layout->wrapper('ckv_admin/layout');
		$this->layout->create ( 'admin/roles/resources', $this->data );
	}
	
	function update() {
		$this->_checkedNodes = explode ( ",", $_POST ['checkedNodes'] );
		$this->_role = $_POST ['role'];
		
		if ($this->input->post('cancel')){
			redirect('admin/authorizations/admin_roles/index');
		}
		
		//update resources and permissions
		foreach ( $this->modules as $module ) {
			//If resource is not existed, add it
			$resourceModule = strtolower ( $module ['folder'] );
			
			if (! $this->resourceExist ( $resourceModule )) {
				$this->resources_m->newResource ( array ('name' => $resourceModule, 'description' => '', 'parent_id' => '' ) );
			}
			
			//Update or add permission
			$this->updatePermission($resourceModule, '');
			

			//Controllers
			$controllers = $this->modules_m->getControllers($module['folder']);
			
			foreach($controllers as $controller){
				//If resource is not existed, add it
				$resourceModuleController = strtolower($module['folder'].'/'.$controller);
				if (!$this->resourceExist($resourceModuleController)){
					$this->resources_m->newResource(array(
						'name' => $resourceModuleController
						, 'description' => ''
						, 'parent_id' => $resourceModule
					));
				}
				
				//Update or add permission
				$this->updatePermission($resourceModuleController, '');
				
				$methods = $this->modules_m->getMethods($module['folder'], $controller);
				foreach($methods as $privilege){
					$this->updatePermission($resourceModuleController, $privilege);
				}
			}
			
			//Update or add permission
			$this->updatePermission ( $resourceModule, '' );
		}
		//$this->cache->delete('_acl_');
		//$this->logger->info('Update phan quyen, quan ly resources he thong', USER_ACTION_CONFIG_SYTEM);
		$this->session->set_flashdata ( 'success', $this->lang->line ( 'permission_update_success' ) );
		redirect ( 'admin/authorizations/admin_roles' );
	}
	
	private function updatePermission($resource = '', $privilege = '') {
		if ($this->permissionExist ( $resource, $privilege )) {
			if ($this->isAllowed ( $resource, $privilege ))
				$this->permissions_m->updatePermission ( $this->_role, $resource, $privilege, array ('allow' => 1 ) );
			else
				$this->permissions_m->updatePermission ( $this->_role, $resource, $privilege, array ('allow' => 0 ) );
		} else {
			//Insert permission
			if ($this->isAllowed ( $resource, $privilege ))
				$this->permissions_m->newPermission ( $this->_role, $resource, $privilege, array ('allow' => 1 ) );
			else
				$this->permissions_m->newPermission ( $this->_role, $resource, $privilege, array ('allow' => 0 ) );
		}
	}
	
	private function isAllowed($resourceName, $privilege) {
		if ($privilege)
			$resourceName = $resourceName . "/" . $privilege;
		foreach ( $this->_checkedNodes as $node ) {
			if (strtolower ( $resourceName ) == $node) {
				return true;
			}
		}
		return false;
	}
	
	private function resourceExist($resourceName) {
		if ($this->resources_m->getResource ( array ('name' => $resourceName ) ))
			return true;
		else
			return false;
	}
	
	private function permissionExist($resource = '', $privilege = '') {
		$params = array ('role' => $this->_role, 'resource' => $resource, 'privilege' => $privilege );
		if ($this->permissions_m->getPermissions ( $params ))
			return true;
		else
			return false;
	}
	
	private function isCheckedNode($nodeId, $checkedIds = array()) {
		foreach ( $checkedIds as $checkedId ) {
			if (strcasecmp($nodeId, $checkedId) == 0){
				return true;
			}
		}
		return false;
	}
	
	private function prepareJsonTree($checkedIds = array()) {
		$content = "";
		
		// Root note
		$content = $content . "[{\"text\":\"Modules\",\"id\":\"1\",\"depth\":\"0\",\"leaf\":false,\"checked\":\"true\", \"children\":[\n";
		
		// Get modules
		$i = 0;
		foreach ( $this->modules as $module ) {
			if ($i > 0)
				$content = $content . ",";
				
			// Get contrllers
			$controllers = $this->modules_m->getAdminControllers( $module ['folder'] );
			$id = strtolower ( $module ['folder'] );
			$checkedStatus = $this->isCheckedNode ( $id, $checkedIds ) ? ",\"checked\":\"true\"" : "";
			if (!$controllers) {
				$content = $content . "{\"text\":\"" . $module ['name'] . ' (' . $module ['folder'] . ')' . "\",\"id\":\"" . $id . "\",\"depth\":\"0\",\"leaf\":true" . $checkedStatus;
			} else {
				$content = $content . "{\"text\":\"" . $module ['name'] . ' (' . $module ['folder'] . ')'  . "\",\"id\":\"" . $id . "\",\"depth\":\"0\",\"leaf\":false" . $checkedStatus;
				$content = $content.", \"children\":[\n";	//start controller children
				
				$j = 0;
				foreach ($controllers as $controller){
					if ($j > 0)
						$content = $content.",";
					
					// Get methods
					$methods = $this->modules_m->getMethods($module['folder'], $controller);
					$descriptions = $this->modules_m->getDescriptions($module['folder'], $controller);
					
					$id = strtolower($module['folder']."/".$controller);
					$checkedStatus = $this->isCheckedNode($id, $checkedIds)?",\"checked\":\"true\"":"";
					if (!$methods)
						$content = $content."{\"text\":\"".$controller."\",\"id\":\"".$id."\",\"depth\":\"0\",\"leaf\":true".$checkedStatus;
					else { 
						$content = $content."{\"text\":\"".$controller."\",\"id\":\"".$id."\",\"depth\":\"0\",\"leaf\":false".$checkedStatus;
						$content = $content.", \"children\":[\n";	//start method children
						$k = 0;
						foreach($methods as $method){
							if ($k > 0)
								$content = $content.",";
							$id = strtolower($module['folder']."/".$controller."/".$method);
							$checkedStatus = $this->isCheckedNode($id, $checkedIds)?",\"checked\":\"true\"":"";
							$content = $content."{\"text\":\"".$method."\",\"id\":\"".$id."\",\"depth\":\"0\",";
							if(!empty($descriptions)) {
								$content = $content."\"rel\":\"( ".$descriptions[$k]." )\",";
							}
							$content .= "\"leaf\":true".$checkedStatus."}";
							$k++;		
						}
						$content = $content."]\n"; 	//end method children
					}
					
					$content = $content."}\n";
					$j++;
				}
				
				$content = $content."]\n";	//end controller children
			}
			
			$content = $content . "}\n";
			$i ++;
		}
		
		$content = $content . "]}]\n"; //End root note
		/*

		$file = fopen ( APPPATH . 'assets/json/treesample.json', "w" );
		fwrite ( $file, $content );
		fclose ( $file );
		*/
		file_put_contents(APPPATH . 'assets/json/treesample.json',$content);
	}
}
?>